package cn.monkey.state.bean;

import java.util.Map;
import java.util.concurrent.*;


public class RefreshScheduler {

    private final ScheduledExecutorService scheduledExecutorService;

    private final Map<Refreshable, Runnable> commandMap;

    public RefreshScheduler(int nThread) {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(nThread);
        commandMap = new ConcurrentHashMap<>();
    }

    public void addTask(Refreshable refreshable) {
        Runnable runnable = this.commandMap.computeIfAbsent(refreshable, (r) -> r::refresh);
        this.scheduledExecutorService.scheduleAtFixedRate(runnable,
                refreshable.delay(),
                refreshable.timeIntervalMs(),
                TimeUnit.MILLISECONDS);
    }

    public void removeTask(Refreshable refreshable) {
        if (this.scheduledExecutorService instanceof ThreadPoolExecutor threadPoolExecutor) {
            Runnable runnable = this.commandMap.remove(refreshable);
            if (runnable != null) {
                BlockingQueue<Runnable> queue = threadPoolExecutor.getQueue();
                queue.remove(runnable);
            }
        }
    }
}
